package com.panshi.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.panshi.modules.domain.UserMember;
import com.panshi.modules.mapper.UserMapper;
import com.panshi.modules.service.UserService;
import com.panshi.modules.service.VerifyCodeService;
import com.panshi.util.BaseUpload;
import com.panshi.util.EmailUtils;
import com.panshi.vo.ItemQueryUserVo;
import com.panshi.vo.R;
import com.panshi.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private VerifyCodeService verifyCodeService;


    @Override
    public List<UserVO> listUser() {
        List<UserMember> userMembers = userMapper.selectList(null);

        if (CollectionUtils.isEmpty(userMembers)) {
            return new ArrayList<>();
        }
        List<UserVO> list = new ArrayList<>();
        for(UserMember userMember : userMembers){
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(userMember , userVO);
            list.add(userVO);
        }
        return list;
    }

    @Override
    public int addUser(UserMember userMember) {
        return userMapper.insert(userMember);
    }

    @Override
    public int editUser(UserVO userVO) {
        UserMember userMember = getUserMember(userVO);
        return userMapper.updateById(userMember);
    }

    @Override
    public int delUser(Integer id) {
        return userMapper.deleteById(id);
    }

    /**
     * 通过 id 获取 用户信息
     * @param id
     * @return
     */
    @Override
    public UserVO getUserById(Integer id) {
        UserMember userMember = userMapper.selectById(id);
        return getUserVO(userMember);
    }

    /**
     * 通过 phone 获取用户信息
     * @param phone
     * @return
     */
    @Override
    public UserVO getUserByPhone(String phone) {
        UserMember userMember = userMapper.selectOne(new QueryWrapper<UserMember>().select("id","phone","password").eq("phone", phone));
        return getUserVO(userMember);
    }

    /**
     * 通过 email 获取用户信息
     * @param email
     * @return
     */
    @Override
    public UserVO getUserByEmail(String email) {
        UserMember userMember = userMapper.selectOne(new QueryWrapper<UserMember>().select("id","email","password").eq("email", email));
        return getUserVO(userMember);
    }

    /**
     *   //根据用户ID查询指定用户
     * @param id
     * @return
     */
    @Override
    public UserMember selectByUserInfo(Integer id) {

        return this.userMapper.selectById(id);
    }

    /**
     * 发送邮箱验证码
     * @param
     * @return
     */
    @Override
    public R sendEmail(Integer userId,String userName,String type) {

        List<UserMember> list = userMapper.selectList(new QueryWrapper<UserMember>().select("id").eq("email", userName).ne("id",userId));

        if(list.size()>0){
            return R.error().msg("该邮箱帐号已经绑定");
        }

        if(verifyCodeService.sendUpdateEmail(userName,type)){
            return R.ok().msg("发送邮箱验证码成功");
        }

        return R.error().msg("发送邮箱验证码失败");
    }

    //校验邮箱验证码是否正确
    @Override
    public R checkEmailCode(Integer userId,String userName,String code,String type){
        System.out.println("邮箱用户ID      "+userId+"         "+userName+"               "+code+"              "+type);
        Object sendEmail = null;
        if("0".equals(type) && redisTemplate.hasKey("user:email:send:"+userName)){
            sendEmail = redisTemplate.opsForValue().get("user:email:send:"+userName);
        }else if("1".equals(type) && redisTemplate.hasKey("user:email:update:send:"+userName)){
            sendEmail = redisTemplate.opsForValue().get("user:email:update:send:"+userName);
            UserMember userMemberUpdate = new UserMember();
            userMemberUpdate.setId(userId);
            userMemberUpdate.setEmail(userName);
            userMapper.updateById(userMemberUpdate);
        }
        if(code.equals(sendEmail.toString())){
            return R.ok().msg("邮箱验证码输入正确");
        }
        return R.error().msg("邮箱验证码输入错误");
    }
    /**
     * 发送短信验证码
     * @param
     * @return
     */
    @Override
    public R sendIphone(Integer userId,String userName, String type) {

        List<UserMember> list = userMapper.selectList(new QueryWrapper<UserMember>().select("id").eq("phone", userName).ne("id",userId));

        if(list.size()>0){
            return R.error().msg("该手机帐号已经绑定");
        }

        if(verifyCodeService.sendUpdateSms(userName,type)){
            return R.ok().msg("发送短信验证码成功");
        }

        return R.error().msg("发送短信验证码失败");
    }
    /**
     * 校验短信验证码是否正确
     * @param
     * @return
     */
    @Override
    public R checkIphoneCode(Integer userId,String userName, String code, String type) {

        System.out.println("短信用户ID      "+userId+"         "+userName+"               "+code+"              "+type);
        Object sendIphone = null;
        if("0".equals(type) && redisTemplate.hasKey("user:iphone:send:"+userName)){
            sendIphone = redisTemplate.opsForValue().get("user:iphone:send:"+userName);
        }else if("1".equals(type) && redisTemplate.hasKey("user:iphone:update:send:"+userName)){
            sendIphone = redisTemplate.opsForValue().get("user:iphone:update:send:"+userName);
            UserMember userMemberUpdate = new UserMember();
            userMemberUpdate.setId(userId);
            userMemberUpdate.setPhone(userName);
            userMapper.updateById(userMemberUpdate);
        }
        if(code.equals(sendIphone.toString())){
            return R.ok().msg("短信验证码输入正确");
        }
        return R.error().msg("短信验证码输入错误");
    }

    //根据指定邮箱名查用户ID
    @Override
    public int queryUserId(int type,String userName) {
        UserMember userMember = null;
        if(type!=-1){
            if(type == 0){
                userMember = this.userMapper.selectOne(new QueryWrapper<UserMember>().eq("phone",userName));
            }else if(type == 1){
                userMember = this.userMapper.selectOne(new QueryWrapper<UserMember>().eq("email",userName));
            }
        }
        return userMember==null ? -1 : userMember.getId();
    }
    //根据类型判断根据邮箱还是验证码查询用户ID
    @Override
    public Long getUserLoginId(String userName, int type) {
        return userMapper.getUserLoginId(userName,type);
    }

    ;

    /**
     *  修改指定用户ID下用户信息
     * @param itemQueryVo
     * @return
     */
    @Override
    public int updateUserInfo(ItemQueryUserVo itemQueryVo) {
        return userMapper.updateUserInfoById(itemQueryVo);
    }

    @Override
    public String updateUserHeadBaseCode(ItemQueryUserVo itemQueryUserVo) {
        String url = "";
        try {
            //String path = ResourceUtils.getURL("classpath:").getPath();
            BaseUpload baseUpload = new BaseUpload();
            url =baseUpload.put64myImage(itemQueryUserVo.getFile());
        }catch (Exception e){
            e.printStackTrace();
        }
        UserMember userMemberUpdate = new UserMember();
        //判断昵称
        if(!StringUtils.isEmpty(url)){
            userMemberUpdate.setPhotoPath(url);
            userMemberUpdate.setId(itemQueryUserVo.getId().intValue());
            userMapper.updateById(userMemberUpdate);
        }


        return url;
    }

    // UserMember 转 UserVO
    public UserVO getUserVO(UserMember userMember){
        UserVO userVO = new UserVO();
        if(userMember == null){
            return null;
        }
        BeanUtils.copyProperties(userMember,userVO);
        return userVO;
    }

    //UserVO 转 UserMember
    public UserMember getUserMember(UserVO userVO){
        UserMember userMember = new UserMember();
        if(userVO == null){
            return null;
        }
        BeanUtils.copyProperties(userVO,userMember);
        return userMember;
    }
}
